package com.apotik.legenda.dialog;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.Color;

import javax.swing.JButton;

import com.apotik.legenda.dao.ProductDao;
import com.apotik.legenda.model.Product;
import com.apotik.legenda.model.User;
import com.apotik.legenda.observer.GeneralObserver;
import com.apotik.legenda.util.AppUtil;
import com.apotik.legenda.util.CalendarUtil;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.border.EmptyBorder;

import java.awt.BorderLayout;

import javax.swing.border.MatteBorder;

import java.awt.GridLayout;

import javax.swing.SwingConstants;

public class AddEditProductDialog extends JDialog implements ActionListener, FocusListener {
	private static final long serialVersionUID = 1L;

	private JPanel panel;
	
	private JTextField textFieldNama;
	private JTextField textFieldKode;
	private JTextField textFieldStok;
	
	private JButton btnSave;
	private JButton btnCancel;
	
	private User user;
	private GeneralObserver observer;
	private Product currentProduct;
	private int activePageIndex = -1;
	private JTextField textFieldUnit;
	private JTextField textFieldHargaJual;
	private JTextField textFieldHargaBeli;
	
	
	public AddEditProductDialog(String title, User user, GeneralObserver observer) {
		this.user = user;
		this.observer = observer;
		
		setTitle(title);
		setSize(387, 240);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
					AddEditProductDialog.this.setVisible(false);
				} else if(e.getKeyCode()==KeyEvent.VK_ENTER){
					
				}
			}
		});
		
		
		panel = new JPanel();
		panel.setBorder(new EmptyBorder(7, 7, 7, 7));
		getContentPane().add(panel);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_5 = new JPanel();
		panel.add(panel_5, BorderLayout.NORTH);
		panel_5.setLayout(new GridLayout(0, 2, 0, 5));
		
		JLabel lblNama = new JLabel("Nama Barang");
		panel_5.add(lblNama);
		
		textFieldNama = new JTextField();
		panel_5.add(textFieldNama);
		textFieldNama.setColumns(10);
		
		JLabel lblKode = new JLabel("Kode Barang");
		panel_5.add(lblKode);
		
		textFieldKode = new JTextField();
		panel_5.add(textFieldKode);
		textFieldKode.setColumns(10);
		
		JLabel lblStok = new JLabel("Stok Tersedia");
		panel_5.add(lblStok);
		
		textFieldStok = new JTextField();
		panel_5.add(textFieldStok);
		textFieldStok.setColumns(10);
		
		JLabel lblUnit = new JLabel("Unit");
		panel_5.add(lblUnit);
		
		textFieldUnit = new JTextField();
		panel_5.add(textFieldUnit);
		textFieldUnit.setColumns(10);
		
		JLabel lblHargaBeli = new JLabel("Harga Beli");
		panel_5.add(lblHargaBeli);
		
		textFieldHargaBeli = new JTextField();
		textFieldHargaBeli.setHorizontalAlignment(SwingConstants.RIGHT);
		textFieldHargaBeli.addFocusListener(this);
		panel_5.add(textFieldHargaBeli);
		textFieldHargaBeli.setColumns(10);
		
		JLabel lblHargaJual = new JLabel("Harga Jual");
		panel_5.add(lblHargaJual);
		
		textFieldHargaJual = new JTextField();
		textFieldHargaJual.setHorizontalAlignment(SwingConstants.RIGHT);
		textFieldHargaJual.addFocusListener(this);
		panel_5.add(textFieldHargaJual);
		textFieldHargaJual.setColumns(10);
		
		JPanel panel_1 = new JPanel();
		getContentPane().add(panel_1, BorderLayout.SOUTH);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new MatteBorder(1, 0, 0, 0, (Color) Color.GRAY));
		panel_1.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new EmptyBorder(3, 3, 3, 3));
		panel_2.add(panel_3);
		panel_3.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_4 = new JPanel();
		panel_3.add(panel_4, BorderLayout.EAST);
		
		btnSave = new JButton("Save");
		btnSave.addActionListener(this);
		panel_4.add(btnSave);
		
		btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(this);
		panel_4.add(btnCancel);
		
		
	}
	
	@SuppressWarnings("rawtypes")
	public void fillInTheFields(Vector vectorRow, int activePageIndex){
		if(vectorRow!=null){
			this.activePageIndex = activePageIndex;
			this.currentProduct = (Product) vectorRow.get(vectorRow.size()-1);
			
			textFieldNama.setText(currentProduct.getProductName());
			textFieldKode.setText(currentProduct.getProductCode());
			textFieldStok.setText(Integer.toString(currentProduct.getAvailableStock()));
			textFieldUnit.setText(currentProduct.getProductUnit());
			textFieldHargaBeli.setText(AppUtil.formatStringIDR(currentProduct.getPriceBuy().intValue()));
			textFieldHargaJual.setText(AppUtil.formatStringIDR(currentProduct.getPriceSell().intValue()));
		}
	}
	
	@SuppressWarnings({ })
	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		
		if(obj==btnSave){
			String nama = textFieldNama.getText();
			String kode = textFieldKode.getText();
			String stokStr = textFieldStok.getText();
			String unit = textFieldUnit.getText();
			String hargaBeliStr = textFieldHargaBeli.getText();
			String hargaJualStr = textFieldHargaJual.getText();
			
			int stokInt = 0;
			if(AppUtil.isNumber(stokStr)){
				stokInt = Integer.parseInt(stokStr);
			}
			
			if(hargaBeliStr.trim().isEmpty()){
				hargaBeliStr = "0";
			}
			String hargaBeliRemoveDot = AppUtil.removeCharacters(hargaBeliStr, ".");
			
			if(hargaJualStr.trim().isEmpty()){
				hargaJualStr = "0";
			}
			String hargaJualRemoveDot = AppUtil.removeCharacters(hargaJualStr, ".");
			
			Product p = null;
			if(currentProduct!=null){
				Date updatePrice = null;
				
				BigDecimal priceSellBefore = currentProduct.getPriceSell();
				if(!priceSellBefore.equals(new BigDecimal(hargaJualRemoveDot))){
					updatePrice = CalendarUtil.dateNow();
				}
				
				p = currentProduct;
				p.setUpdatedBy(user);
				p.setUpdatedDate(CalendarUtil.dateNow());
				p.setUpdatedPriceDate(updatePrice);
			}else{
				p = new Product();
				p.setCreatedBy(user);
				p.setCreatedDate(CalendarUtil.dateNow());
				p.setActive(true);
			}
			
			p.setProductName(nama);
			p.setProductCode(kode);
			p.setAvailableStock(stokInt);
			p.setProductUnit(unit);
			p.setPriceBuy(new BigDecimal(hargaBeliRemoveDot));
			p.setPriceSell(new BigDecimal(hargaJualRemoveDot));
			
			ProductDao dao = new ProductDao();
			if(dao.saveOrUpdate(p)){
				JOptionPane.showMessageDialog(null, "Sukses", "Success", JOptionPane.INFORMATION_MESSAGE);
			}else{
				JOptionPane.showMessageDialog(null, "Gagal", "Error", JOptionPane.ERROR_MESSAGE);
			}

			
			HashMap<String, Object> hm = new HashMap<>();
			hm.put("activePageIndex", activePageIndex);
			observer.response(hm);
			
			this.setVisible(false);
			
		}else if(obj==btnCancel){
			this.setVisible(false);
		}
	}

	@Override
	public void focusGained(FocusEvent e) {
		Object source = e.getSource();
		
		if(source==textFieldHargaBeli){
			String valStr = textFieldHargaBeli.getText();
			if(valStr.trim().isEmpty()){
				valStr = "0";
			}
			
			String removeDot = AppUtil.removeCharacters(valStr, ".");
			textFieldHargaBeli.setText(removeDot);
			
		}else if(source==textFieldHargaJual){
			String valStr = textFieldHargaJual.getText();
			if(valStr.trim().isEmpty()){
				valStr = "0";
			}
			
			String removeDot = AppUtil.removeCharacters(valStr, ".");
			textFieldHargaJual.setText(removeDot);
		}
	}

	@Override
	public void focusLost(FocusEvent e) {
		Object source = e.getSource();
		
		if(source==textFieldHargaBeli){
			String valStr = textFieldHargaBeli.getText();
			if(valStr.trim().isEmpty()){
				valStr = "";
			}
			
			String removeDot = AppUtil.removeCharacters(valStr, ".");
			if(!AppUtil.isNumber(removeDot)){
				JOptionPane.showMessageDialog(null, "Invalid.\nSilahkan masukkan angka", "Error", JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			textFieldHargaBeli.setText(AppUtil.formatStringIDR(Integer.parseInt(removeDot)));
			
		}else if(source==textFieldHargaJual){
			String valStr = textFieldHargaJual.getText();
			if(valStr.trim().isEmpty()){
				valStr = "";
			}
			
			String removeDot = AppUtil.removeCharacters(valStr, ".");
			if(!AppUtil.isNumber(removeDot)){
				JOptionPane.showMessageDialog(null, "Invalid.\nSilahkan masukkan angka", "Error", JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			textFieldHargaJual.setText(AppUtil.formatStringIDR(Integer.parseInt(removeDot)));
		}
	}
	
}
